<?php
namespace Modules\Activity\Http\Controllers\Admin\YiFanShang;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use \Modules\Activity\Entities\YiFanShang\Sku;
// use \Modules\Activity\Entities\ActivityRecord;

use Validator;
use ThrowException;
use DB;

class SkuController extends Controller
{
    public function index(Request $req)
    {
        $rule = [
            'shang_type' => ['required'],
            'activity_id' => ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $options = $req->all();

        $options['order_by'] = [
            'list_weight' => 'desc',
            'id' => 'asc'
        ];
        // $options['with_count'] = ['records', 'skus'];
        // $options['with'] = ['activity_info'];
        $options['where']['activity_id'] = $req->activity_id;

        $list = Sku::getList($options);

        // $list->each(function ($item) {
        //     $item->sku_stock = $item->skus()->sum('stock');
        // });

        return $list->generateListResponse();
    }

    public function update(Request $req, $uuid)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $item = Sku::getEntity([
            'uuid' => $uuid
        ]);

        DB::beginTransaction();

        if ($req->type === 'update') {
            $info = $req->input('attributes');

            if (@$info['lottery_start_point'] > @$info['lottery_end_point']) {
                ThrowException::Conflict('抽奖开始位置不能大于结束位置');
            }

            $item->update($info);
        }

        $item->updateStock();

        $item->activity->refreshPerRoomTotal();

        DB::commit();

        return [];
    }
}
